package com.yima.baseproj.module.app.equipment_entry;

// EquipmentController.java

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import com.yima.baseproj.module.app.equipment_entry.EquipmentEntryEntity;
import com.yima.baseproj.module.app.equipment_entry.EquipmentEntryService;
import com.yima.baseproj.module.config.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.*;

@Api(tags = "excel导入导出")
@RestController
@RequestMapping("/api/equipment/controller/entry")
public class Controller extends BaseController {

    @Autowired
    private EquipmentEntryService equipmentEntryRepository; // 自动注入实体类的Repository

    @ApiOperation("导入")
    @PostMapping("/import")
    public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file) {
        List<Map<String, Object>> importedData = new ArrayList<>();
        Set<String> duplicateData = new HashSet<>();
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 假设是xlsx格式，如果是xls则使用HSSFWorkbook
            Sheet sheet = workbook.getSheetAt(0);

            // 假设第一行是表头，从第二行开始读取数据
            boolean isHeaderSkipped = false;
            for (Row row : sheet) {
                if (!isHeaderSkipped) {
                    isHeaderSkipped = true; // 跳过表头
                    continue;
                }

                String deviceNo = row.getCell(0).getStringCellValue();
                String count = row.getCell(1).getStringCellValue(); // 假设第二个字段是count，且为数值类型

                EquipmentEntryEntity existingEntry = equipmentEntryRepository.findByDeviceNo(deviceNo);
                if (existingEntry == null) {
                    EquipmentEntryEntity newEntry = new EquipmentEntryEntity();
                    newEntry.setDeviceNo(deviceNo);
                    newEntry.setCount(count); // 假设EquipmentEntryEntity有这个字段
                    equipmentEntryRepository.save(newEntry);
                    importedData.add(Map.of("deviceNo", deviceNo, "count", count));
                } else {
                    duplicateData.add(deviceNo);
                }
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("importedData", importedData);
        result.put("duplicateData", duplicateData);
        return result;
    }

//    @ApiOperation("导入")
//    @PostMapping("/import")
//    public Map<String, String> importExcel(@RequestParam("file") MultipartFile file) {
//        List<String> importedData = new ArrayList<>();
//        Set<String> duplicateData = new HashSet<>();
//        Set<String> imported = new HashSet<>();
//        try {
//            InputStream inputStream = file.getInputStream();
//            Workbook workbook = WorkbookFactory.create(inputStream);
//            Sheet sheet = workbook.getSheetAt(0);
//            for (Row row : sheet) {
//                String deviceNo = row.getCell(0).getStringCellValue();
//                EquipmentEntryEntity existingEntry = equipmentEntryRepository.findByDeviceNo(deviceNo);
//                if (existingEntry == null) {
//                    if (!deviceNo.equals("设备序列号") && !deviceNo.equals("设备号")) {
//                        EquipmentEntryEntity newEntry = new EquipmentEntryEntity();
//                        newEntry.setDeviceNo(deviceNo);
//                        equipmentEntryRepository.save(newEntry);
//                        importedData.add(deviceNo);
//                        imported.add(deviceNo);
//                    }
//                } else {
//                    duplicateData.add(deviceNo);
//                }
//            }
//            workbook.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println("imported" + imported);
//        System.out.println("duplicateData" + duplicateData);
//
//        JSONArray duplicateJSON = new JSONArray();
//        JSONArray importedJSON = new JSONArray();
//
//        for (String item : duplicateData) {
//            duplicateJSON.put(item);
//        }
//
//        for (String item : imported) {
//            importedJSON.put(item);
//        }
//
//        Map<String, String> map = new HashMap<>();
//        map.put("importedData", importedJSON.toString());
//        map.put("duplicateData", duplicateJSON.toString());
//        return map;
//    }

    @ApiOperation("导出")
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=deviceNo.xlsx");
        // 实现导出Excel文件的逻辑
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("deviceNo");
            List<EquipmentEntryEntity> entries = equipmentEntryRepository.findAll();
            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("设备序列号");
            headerRow.createCell(1).setCellValue("备注");
            // 填充数据
            int rowNum = 1;
            for (EquipmentEntryEntity entry : entries) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(entry.getDeviceNo());
                row.createCell(1).setCellValue(entry.getCount());
            }
            // 输出Excel文件
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @ApiOperation("下载模板")
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=deviceNo.xlsx");
        // 实现导出Excel文件的逻辑
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("deviceNo");
            List<EquipmentEntryEntity> entries = equipmentEntryRepository.findAll();
            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("设备序列号");
            headerRow.createCell(1).setCellValue("备注");
            // 输出Excel文件
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}